package org.bluedream.core.module.service.depItem;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import org.bluedream.comm.utils.EmptyUtil;
import org.bluedream.core.module.base.OrgTreeServiceImpl;
import org.bluedream.core.module.dao.depItem.DepItemDao;
import org.bluedream.core.module.entity.depItem.DepItem;
import org.bluedream.core.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName depItemUserService
 * @Description TODO
 * @Author foxsand
 * @Data 2021-07-15 17:15
 * @Version
 */
@Service
@DS("master")
@Transactional(readOnly = true)
public class DepItemService extends OrgTreeServiceImpl<DepItemDao, DepItem> implements IService<DepItem> {
    private static final Logger logger = LoggerFactory.getLogger(DepItemService.class);

    @Override
    public DepItem getById(Serializable id) {
        if (EmptyUtil.isEmpty(id)){
            return new DepItem();
        }else {
            DepItem depItem = super.getById(id);
            if (!"0".equals(depItem.getParentCode())){
                depItem.setParent(super.getById(depItem.getParentCode()));
            }
            return depItem;
        }
    }


    /**
     * 获取树结构数据
     * @param excludeCode 排除的code
     * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
     * @return
     */
    public List<Map<String , Object>> treeData(String excludeCode , String isShowCode){
        return super.treeData(excludeCode , isShowCode , new DepItem());
    }

    @Override
    @Transactional(
            readOnly = false,
            rollbackFor = Exception.class
    )
    public boolean save(DepItem entity) {
        UserUtil.allowSystemNodeSave();
        boolean flag;
        try {
            Map<String , String> newRecordSearchMap = new HashMap<>();
            newRecordSearchMap.put("code" , "getTreeCode");
            newRecordSearchMap.put("org_code" , "getOrgCode");
            super.setIsNewRecord(entity , newRecordSearchMap);
            flag = super.save(entity);
            return flag;
        }catch (Exception e){
            logger.error("保存部门信息失败，错误信息：" + e.getMessage());
            return false;
        }
    }

    @Override
    public DepItem createNextNode(DepItem entity , String... lastChildrenNodeOrderArgs) {
        entity.setParentCode();
        entity = super.createNextNode(entity , lastChildrenNodeOrderArgs);
        return entity;
    }

    public IPage<DepItem> findPage(DepItem entity){
        return super.findPage(entity , null , "tree_Sorts" , "tree_Sort");
    }

}
